from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.meiduo_admin.serializers.orders import OrderInfoSerializer
from apps.meiduo_admin.utils import UserPageNum
from apps.orders.models import OrderInfo


class OrderView(ModelViewSet):
    '''
        订单表的增删改查
    '''
    # 指定查询集
    queryset = OrderInfo.objects.all()
    # 指定序列化器
    serializer_class = OrderInfoSerializer
    # 指定分页器
    pagination_class = UserPageNum
    # 指定权限
    permission_classes = [IsAdminUser]

    # 重写get_queryset方法，根据前端是否传递keyword值返回不同查询结果
    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('keyword')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is None or keyword == '':
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains=keyword)

    # 修改订单状态
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        # 1、根据order_id查询订单对象
        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error': '该订单不存在'})
        # 2、修改订单状态
        status = request.data.get('status')
        order.status = status
        order.save()
        # 3、返回结果
        return Response({
            'order_id':pk,
            'status':status
        })